package network.themis.rms.console.shiro;

import lombok.extern.slf4j.Slf4j;
import network.themis.rms.console.common.model.RestResp;
import network.themis.rms.console.common.util.EncryptUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author ccl
 * @time 2018-07-26 14:26
 * @name ShiroController
 * @desc:
 */
@Slf4j
@RestController
public class ShiroController {
    @PostMapping(value = "/signin")
    public RestResp signin(String username, String password){
        try {
            Subject subject = SecurityUtils.getSubject();
            if(subject.isAuthenticated()){
                return RestResp.success("用户已登录");
            }
            String encrypt = EncryptUtils.encodeSHA256(password);
            UsernamePasswordToken token = new UsernamePasswordToken(username, encrypt);

            subject.login(token);

            return RestResp.success("登录成功", subject.getSession().getId());
        } catch (IncorrectCredentialsException e) {
            log.error("账号或密码错误", e);
            return RestResp.fail("账号或密码错误");
        } catch (LockedAccountException e) {
            log.error("账户已被冻结", e);
            return RestResp.fail("账户已被冻结");
        } catch (AuthenticationException e) {
            log.error("账户不存在", e);
            return RestResp.fail("账户不存在");
        } catch (Exception e) {
            log.error("登录失败", e);
            return RestResp.fail("登录失败");
        }
    }
    @RequestMapping(value = "/signout")
    public RestResp signout(){
        return RestResp.success("退出成功");
    }
    @RequestMapping(value = "/unauth")
    public RestResp unauth(){
        return RestResp.fail("未登录");
    }
}
